package cn.ibizlab.businesscentral.core.product.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.businesscentral.core.product.domain.Product;
import cn.ibizlab.businesscentral.core.product.filter.ProductSearchContext;
import cn.ibizlab.businesscentral.core.product.service.IProductService;

import cn.ibizlab.businesscentral.util.helper.CachedBeanCopier;
import cn.ibizlab.businesscentral.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.businesscentral.core.product.mapper.ProductMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 实体[产品] 服务对象接口实现
 */
@Slf4j
@Service("ProductServiceImpl")
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.sales.service.ICompetitorProductService competitorproductService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.IContractDetailService contractdetailService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.IIncidentService incidentService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.stock.service.IInventoryService inventoryService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.finance.service.IInvoiceDetailService invoicedetailService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.sales.service.IOpportunityProductService opportunityproductService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.product.service.IProductAssociationService productassociationService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.product.service.IProductPriceLevelService productpricelevelService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.product.service.IProductSalesLiteratureService productsalesliteratureService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.product.service.IProductSubstituteService productsubstituteService;

    protected cn.ibizlab.businesscentral.core.product.service.IProductService productService = this;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.sales.service.IQuoteDetailService quotedetailService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.sales.service.ISalesOrderDetailService salesorderdetailService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.product.service.IPriceLevelService pricelevelService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.ISubjectService subjectService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.ITransactionCurrencyService transactioncurrencyService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.IUomScheduleService uomscheduleService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.IUomService uomService;

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.product.service.logic.IProductPublishLogic publishLogic;

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.product.service.logic.IProductReviseLogic reviseLogic;

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.product.service.logic.IProductStopLogic stopLogic;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(Product et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et)))
            return false;
        CachedBeanCopier.copy(get(et.getProductid()),et);
        return true;
    }

    @Override
    public void createBatch(List<Product> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list,batchSize);
    }

    @Override
    @Transactional
    public boolean update(Product et) {
        fillParentData(et);
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("productid",et.getProductid())))
            return false;
        CachedBeanCopier.copy(get(et.getProductid()),et);
        return true;
    }

    @Override
    public void updateBatch(List<Product> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        boolean result=removeById(key);
        return result ;
    }

    @Override
    public void removeBatch(Collection<String> idList) {
        removeByIds(idList);
    }

    @Override
    @Transactional
    public Product get(String key) {
        Product et = getById(key);
        if(et==null){
            et=new Product();
            et.setProductid(key);
        }
        else{
        }
        return et;
    }

    @Override
    public Product getDraft(Product et) {
        fillParentData(et);
        return et;
    }

    @Override
    public boolean checkKey(Product et) {
        return (!ObjectUtils.isEmpty(et.getProductid()))&&(!Objects.isNull(this.getById(et.getProductid())));
    }
    @Override
    @Transactional
    public Product publish(Product et) {
        publishLogic.execute(et);
         return et ;
    }

    @Override
    @Transactional
    public Product revise(Product et) {
        reviseLogic.execute(et);
         return et ;
    }

    @Override
    @Transactional
    public boolean save(Product et) {
        if(!saveOrUpdate(et))
            return false;
        return true;
    }

    @Override
    @Transactional
    public boolean saveOrUpdate(Product et) {
        if (null == et) {
            return false;
        } else {
            return checkKey(et) ? this.update(et) : this.create(et);
        }
    }

    @Override
    public boolean saveBatch(Collection<Product> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
        return true;
    }

    @Override
    public void saveBatch(List<Product> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
    }

    @Override
    @Transactional
    public Product stop(Product et) {
        stopLogic.execute(et);
         return et ;
    }


	@Override
    public List<Product> selectByPricelevelid(String pricelevelid) {
        return baseMapper.selectByPricelevelid(pricelevelid);
    }

    @Override
    public void removeByPricelevelid(String pricelevelid) {
        this.remove(new QueryWrapper<Product>().eq("pricelevelid",pricelevelid));
    }

	@Override
    public List<Product> selectByParentproductid(String productid) {
        return baseMapper.selectByParentproductid(productid);
    }

    @Override
    public void removeByParentproductid(String productid) {
        this.remove(new QueryWrapper<Product>().eq("parentproductid",productid));
    }

	@Override
    public List<Product> selectBySubjectid(String subjectid) {
        return baseMapper.selectBySubjectid(subjectid);
    }

    @Override
    public void removeBySubjectid(String subjectid) {
        this.remove(new QueryWrapper<Product>().eq("subjectid",subjectid));
    }

	@Override
    public List<Product> selectByTransactioncurrencyid(String transactioncurrencyid) {
        return baseMapper.selectByTransactioncurrencyid(transactioncurrencyid);
    }

    @Override
    public void removeByTransactioncurrencyid(String transactioncurrencyid) {
        this.remove(new QueryWrapper<Product>().eq("transactioncurrencyid",transactioncurrencyid));
    }

	@Override
    public List<Product> selectByDefaultuomscheduleid(String uomscheduleid) {
        return baseMapper.selectByDefaultuomscheduleid(uomscheduleid);
    }

    @Override
    public void removeByDefaultuomscheduleid(String uomscheduleid) {
        this.remove(new QueryWrapper<Product>().eq("defaultuomscheduleid",uomscheduleid));
    }

	@Override
    public List<Product> selectByDefaultuomid(String uomid) {
        return baseMapper.selectByDefaultuomid(uomid);
    }

    @Override
    public void removeByDefaultuomid(String uomid) {
        this.remove(new QueryWrapper<Product>().eq("defaultuomid",uomid));
    }


    /**
     * 查询集合 DEFAULT
     */
    @Override
    public Page<Product> searchDefault(ProductSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Product> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Product>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 有效
     */
    @Override
    public Page<Product> searchEffective(ProductSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Product> pages=baseMapper.searchEffective(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Product>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 正在修订
     */
    @Override
    public Page<Product> searchRevise(ProductSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Product> pages=baseMapper.searchRevise(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Product>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 已停用
     */
    @Override
    public Page<Product> searchStop(ProductSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Product> pages=baseMapper.searchStop(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Product>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Product et){
        //实体关系[DER1N_PRODUCT__PRICELEVEL__PRICELEVELID]
        if(!ObjectUtils.isEmpty(et.getPricelevelid())){
            cn.ibizlab.businesscentral.core.product.domain.PriceLevel pricelevel=et.getPricelevel();
            if(ObjectUtils.isEmpty(pricelevel)){
                cn.ibizlab.businesscentral.core.product.domain.PriceLevel majorEntity=pricelevelService.get(et.getPricelevelid());
                et.setPricelevel(majorEntity);
                pricelevel=majorEntity;
            }
            et.setPricelevelname(pricelevel.getPricelevelname());
        }
        //实体关系[DER1N_PRODUCT__PRODUCT__PARENTPRODUCTID]
        if(!ObjectUtils.isEmpty(et.getParentproductid())){
            cn.ibizlab.businesscentral.core.product.domain.Product parentproduct=et.getParentproduct();
            if(ObjectUtils.isEmpty(parentproduct)){
                cn.ibizlab.businesscentral.core.product.domain.Product majorEntity=productService.get(et.getParentproductid());
                et.setParentproduct(majorEntity);
                parentproduct=majorEntity;
            }
            et.setParentproductname(parentproduct.getProductname());
        }
        //实体关系[DER1N_PRODUCT__SUBJECT__SUBJECTID]
        if(!ObjectUtils.isEmpty(et.getSubjectid())){
            cn.ibizlab.businesscentral.core.base.domain.Subject subject=et.getSubject();
            if(ObjectUtils.isEmpty(subject)){
                cn.ibizlab.businesscentral.core.base.domain.Subject majorEntity=subjectService.get(et.getSubjectid());
                et.setSubject(majorEntity);
                subject=majorEntity;
            }
            et.setSubjectname(subject.getTitle());
        }
        //实体关系[DER1N_PRODUCT__TRANSACTIONCURRENCY__TRANSACTIONCURRENCYID]
        if(!ObjectUtils.isEmpty(et.getTransactioncurrencyid())){
            cn.ibizlab.businesscentral.core.base.domain.TransactionCurrency transactioncurrency=et.getTransactioncurrency();
            if(ObjectUtils.isEmpty(transactioncurrency)){
                cn.ibizlab.businesscentral.core.base.domain.TransactionCurrency majorEntity=transactioncurrencyService.get(et.getTransactioncurrencyid());
                et.setTransactioncurrency(majorEntity);
                transactioncurrency=majorEntity;
            }
            et.setCurrencyname(transactioncurrency.getCurrencyname());
        }
        //实体关系[DER1N_PRODUCT__UOMSCHEDULE__DEFAULTUOMSCHEDULEID]
        if(!ObjectUtils.isEmpty(et.getDefaultuomscheduleid())){
            cn.ibizlab.businesscentral.core.base.domain.UomSchedule defaultuomschedule=et.getDefaultuomschedule();
            if(ObjectUtils.isEmpty(defaultuomschedule)){
                cn.ibizlab.businesscentral.core.base.domain.UomSchedule majorEntity=uomscheduleService.get(et.getDefaultuomscheduleid());
                et.setDefaultuomschedule(majorEntity);
                defaultuomschedule=majorEntity;
            }
            et.setDefaultuomschedulename(defaultuomschedule.getUomschedulename());
        }
        //实体关系[DER1N_PRODUCT__UOM__DEFAULTUOMID]
        if(!ObjectUtils.isEmpty(et.getDefaultuomid())){
            cn.ibizlab.businesscentral.core.base.domain.Uom defaultuom=et.getDefaultuom();
            if(ObjectUtils.isEmpty(defaultuom)){
                cn.ibizlab.businesscentral.core.base.domain.Uom majorEntity=uomService.get(et.getDefaultuomid());
                et.setDefaultuom(majorEntity);
                defaultuom=majorEntity;
            }
            et.setDefaultuomname(defaultuom.getUomname());
        }
    }




    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith("insert")) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("update")) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("delete")) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    public List<Product> getProductByIds(List<String> ids) {
         return this.listByIds(ids);
    }

    @Override
    public List<Product> getProductByEntities(List<Product> entities) {
        List ids =new ArrayList();
        for(Product entity : entities){
            Serializable id=entity.getProductid();
            if(!ObjectUtils.isEmpty(id)){
                ids.add(id);
            }
        }
        if(ids.size()>0)
           return this.listByIds(ids);
        else
           return entities;
    }

}



